package cn.schoolwow.quickdao.test.module.business.user.dql.general.flow;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.test.entity.Department;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Assert;

import java.util.Map;

public class GroupDepartmentProcessFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DAO dao = flowContext.checkInstanceData(DAO.class);
        Map<Long,Integer> parentIdDepartmentCountMap = (Map<Long, Integer>) flowContext.checkData("parentIdDepartmentCountMap");

        JSONArray array = dao.query(Department.class)
                .groupBy("parentId")
                .addColumnAs("count(id)", "departmentCount")
                .addColumnAs("parentId", "parentId")
                .addNotNullQuery("parentId")
                .having("count(id)>0")
                .execute()
                .getArray();
        for(int i=0;i<array.size();i++){
            JSONObject o = array.getJSONObject(i);
            Long parentId = o.getLong("parentId");

            Integer departmentCount = o.getInteger("departmentCount");
            Integer expectDepartmentCount = parentIdDepartmentCountMap.get(parentId);
            Assert.assertEquals(departmentCount, expectDepartmentCount);
        }
    }

    @Override
    public String name() {
        return "分组查询部门个数信息";
    }

}
